<?php

declare(strict_types=1);

namespace App\Listener;

use App\JsonRpc\RouteService;
use App\JsonRpc\ServiceService;
use App\JsonRpc\TargetService;
use App\JsonRpc\UpstreamService;
use Hyperf\Event\Annotation\Listener;
use Psr\Container\ContainerInterface;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Framework\Event\OnStart;
use Hyperf\Framework\Event\MainWorkerStart;
use Hyperf\Di\Annotation\Inject;
use function Hyperf\Support\env;
use Hyperf\Logger\LoggerFactory;
use Psr\Log\LoggerInterface;

#[Listener]
class BootApplicationListener implements ListenerInterface
{
    /**
     * @var ServiceService
     */
    #[Inject]
    protected  $serviceService;

    /**
     * @var RouteService
     */
    #[Inject]
    protected  $routeService;

    /**
     * @var UpstreamService
     */
    #[Inject]
    protected  $upstreamService;

    /**
     * @var TargetService
     */
    #[Inject]
    protected  $targetService;

    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(ContainerInterface $container)
    {
        $this->logger = $container->get(LoggerFactory::class)->get('hyperf');
    }

    public function listen(): array
    {
        return [
            MainWorkerStart::class,
        ];
    }

    public function process(object $event): void
    {
        // 获取当前时间
        $currentTime = date("Y-m-d H:i:s",time());
        if ($event instanceof MainWorkerStart) {
            // 获取本机端口
            $currentHttpPort = (int)env("HTTP_SEVER_PORT",9510);
            // 获取本机地址
            $currentHttpIp = $this->targetService->getCurrentIp();
            if($currentHttpIp['code'] != 0){
                $this->logger->info(sprintf('[%s] %s', $currentTime, "获取本机IP失败"));
            }
            // 创建服务
            $servieInfo = $this->serviceService->getService(env("KONG_SERVICE"));
            if($servieInfo["code"] != 0){
                // 定义请求数据
                $newServiceData = [
                    "name" => env("KONG_SERVICE"),
                    "url"=> "http://".$currentHttpIp["data"].':'.$currentHttpPort,
                    "retries" => 3
                ];
                $resService = $this->serviceService->createService($newServiceData);
                if($resService["code"] != 0){
                    $this->logger->info(sprintf('[%s] %s', $currentTime, "创建Kong Service失败"));
                }else{
                    // 打印服务注册成功日志
                    $this->logger->info(sprintf('[%s] %s', $currentTime, "创建Kong Service成功"));
                }
            }

            // 创建路由
            $routeInfo = $this->routeService->getRoute(env("KONG_ROUTE"));
            if($routeInfo["code"] != 0){
                // 创建路由
                $resRoute = $this->routeService->createRouteBindService(env("KONG_SERVICE"),["paths"=>env("KONG_ROUTE_PATHS"),"name"=>env("KONG_ROUTE")]);
                if($resRoute["code"] != 0){
                    $this->logger->info(sprintf('[%s] %s', $currentTime, "创建Kong Route失败"));
                }else{
                    // 打印路由注册成功日志
                    $this->logger->info(sprintf('[%s] %s', $currentTime, "创建Kong Route成功"));
                }
            }

            // 创建upstream
            $upstreamInfo = $this->upstreamService->getUpstream(env("KONG_UPSTREAM"));
            if($upstreamInfo["code"] != 0){
                $resUpstreamInfo = $this->upstreamService->createUpstream(["name"=>env("KONG_UPSTREAM")]);
                if($resUpstreamInfo["code"] != 0){
                    $this->logger->info(sprintf('[%s] %s', $currentTime, "创建Kong Upstream失败"));
                }else{
                    // 打印上游注册成功日志
                    $this->logger->info(sprintf('[%s] %s', $currentTime, "创建Kong Upstream成功"));
                }
                // 绑定服务上游
                $updateService = $this->serviceService->editService(env("KONG_SERVICE"),["host"=>env("KONG_UPSTREAM")]);
                if($updateService["code"] != 0){
                    $this->logger->info(sprintf('[%s] %s', $currentTime, "绑定Service Upstream失败"));
                }else{
                    $this->logger->info(sprintf('[%s] %s', $currentTime, "绑定Service Upstream失败"));
                }
            }

            // 创建Target
            $targetInfo = $this->targetService->getTarget(env("KONG_UPSTREAM"),$currentHttpIp['data'].':'.$currentHttpPort);
            if($targetInfo["code"] != 0){
                $resTarget = $this->targetService->createTarget(env("KONG_UPSTREAM"),["target"=>$currentHttpIp['data'].':'.$currentHttpPort]);
                if($resTarget["code"] != 0){
                    $this->logger->info(sprintf('[%s] %s', $currentTime, "创建Kong Target失败"));
                }else{
                    // 打印Target注册成功日志
                    $this->logger->info(sprintf('[%s] %s', $currentTime, "创建Kong Target成功"));
                }
            }

        }
    }
}
